
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
  <head>
    <meta charset="utf-8" />
    <title>概述 &#8212; Python 3.7.8 文档</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <script type="text/javascript" src="../_static/translations.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="在 Python 3.7.8 文档 中搜索"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="关于这些文档" href="../about.html" />
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="copyright" title="版权所有" href="../copyright.html" />
    <link rel="next" title="稳定的应用程序二进制接口" href="stable.html" />
    <link rel="prev" title="Python/C API 参考手册" href="index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/c-api/intro.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
    
    
    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
 

  </head><body>
  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="stable.html" title="稳定的应用程序二进制接口"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="index.html" title="Python/C API 参考手册"
             accesskey="P">上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python/C API 参考手册</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="introduction">
<span id="api-intro"></span><h1>概述<a class="headerlink" href="#introduction" title="永久链接至标题">¶</a></h1>
<p>Python 的应用编程接口（API）使得 C 和 C++ 程序员可以在多个层级上访问 Python 解释器。该 API 在 C++ 中同样可用，但为简化描述，通常将其称为 Python/C API。使用 Python/C API 有两个基本的理由。第一个理由是为了特定目的而编写 <em>扩展模块</em>；它们是扩展 Python 解释器功能的 C 模块。这可能是最常见的使用场景。第二个理由是将 Python 用作更大规模应用的组件；这种技巧通常被称为在一个应用中 <em class="dfn">embedding</em> Python。</p>
<p>编写扩展模块的过程相对来说更易于理解，可以通过“菜谱”的形式分步骤介绍。使用某些工具可在一定程度上自动化这一过程。虽然人们在其他应用中嵌入 Python 的做法早已有之，但嵌入 Python 的过程没有编写扩展模块那样方便直观。</p>
<p>许多 API 函数在你嵌入或是扩展 Python 这两种场景下都能发挥作用；此外，大多数嵌入 Python 的应用程序也需要提供自定义扩展，因此在尝试在实际应用中嵌入 Python 之前先熟悉编写扩展应该会是个好主意。</p>
<div class="section" id="coding-standards">
<h2>代码标准<a class="headerlink" href="#coding-standards" title="永久链接至标题">¶</a></h2>
<p>如果你想要编写可包含于 CPython 的 C 代码，你 <strong>必须</strong> 遵循在 <span class="target" id="index-38"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0007"><strong>PEP 7</strong></a> 中定义的指导原则和标准。这些指导原则适用于任何你所要扩展的 Python 版本。在编写你自己的第三方扩展模块时可以不必遵循这些规范，除非你准备在日后向 Python 贡献这些模块。</p>
</div>
<div class="section" id="include-files">
<span id="api-includes"></span><h2>包含文件<a class="headerlink" href="#include-files" title="永久链接至标题">¶</a></h2>
<p>使用 Python/C API 所需要的全部函数、类型和宏定义可通过下面这行语句包含到你的代码之中：</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#define PY_SSIZE_T_CLEAN</span>
<span class="cp">#include</span> <span class="cpf">&lt;Python.h&gt;</span><span class="cp"></span>
</pre></div>
</div>
<p>这意味着包含以下标准头文件：<code class="docutils literal notranslate"><span class="pre">&lt;stdio.h&gt;</span></code>，<code class="docutils literal notranslate"><span class="pre">&lt;string.h&gt;</span></code>，<code class="docutils literal notranslate"><span class="pre">&lt;errno.h&gt;</span></code>，<code class="docutils literal notranslate"><span class="pre">&lt;limits.h&gt;</span></code>，<code class="docutils literal notranslate"><span class="pre">&lt;assert.h&gt;</span></code> 和 <code class="docutils literal notranslate"><span class="pre">&lt;stdlib.h&gt;</span></code>（如果可用）。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>由于 Python 可能会定义一些能在某些系统上影响标准头文件的预处理器定义，因此在包含任何标准头文件之前，你 <em>必须</em> 先包含 <code class="file docutils literal notranslate"><span class="pre">Python.h</span></code>。</p>
<p>It is recommended to always define <code class="docutils literal notranslate"><span class="pre">PY_SSIZE_T_CLEAN</span></code> before including
<code class="docutils literal notranslate"><span class="pre">Python.h</span></code>.  See <a class="reference internal" href="arg.html#arg-parsing"><span class="std std-ref">解析参数并构建值变量</span></a> for a description of this macro.</p>
</div>
<p>Python.h 所定义的全部用户可见名称（由包含的标准头文件所定义的除外）都带有前缀 <code class="docutils literal notranslate"><span class="pre">Py</span></code> 或者 <code class="docutils literal notranslate"><span class="pre">_Py</span></code>。以 <code class="docutils literal notranslate"><span class="pre">_Py</span></code> 打头的名称是供 Python 实现内部使用的，不应被扩展编写者使用。结构成员名称没有保留前缀。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>User code should never define names that begin with <code class="docutils literal notranslate"><span class="pre">Py</span></code> or <code class="docutils literal notranslate"><span class="pre">_Py</span></code>. This
confuses the reader, and jeopardizes the portability of the user code to
future Python versions, which may define additional names beginning with one
of these prefixes.</p>
</div>
<p>头文件通常会与 Python 一起安装。在 Unix 上，它们位于以下目录：<code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/include/pythonversion/</span></code> 和 <code class="file docutils literal notranslate"><em><span class="pre">exec_prefix</span></em><span class="pre">/include/pythonversion/</span></code>，其中 <span class="target" id="index-39"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">prefix</span></code> 和 <span class="target" id="index-40"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">exec_prefix</span></code> 是由向 Python 的 <strong class="program">configure</strong> 脚本传入的对应形参所定义，而 <em>version</em> 则为 <code class="docutils literal notranslate"><span class="pre">'%d.%d'</span> <span class="pre">%</span> <span class="pre">sys.version_info[:2]</span></code>。在 Windows 上，头文件安装于 <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/include</span></code>，其中 <span class="target" id="index-41"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">prefix</span></code> 是向安装程序指定的安装目录。</p>
<p>要包含头文件，请将两个目录（如果不同）都放到你所用编译器的包含搜索路径中。请 <em>不要</em> 将父目录放入搜索路径然后使用 <code class="docutils literal notranslate"><span class="pre">#include</span> <span class="pre">&lt;pythonX.Y/Python.h&gt;</span></code>；这将使得多平台编译不可用，因为 <span class="target" id="index-42"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">prefix</span></code> 下平台无关的头文件需要包含来自 <span class="target" id="index-43"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">exec_prefix</span></code> 下特定平台的头文件。</p>
<p>C++ users should note that although the API is defined entirely using C, the
header files properly declare the entry points to be <code class="docutils literal notranslate"><span class="pre">extern</span> <span class="pre">&quot;C&quot;</span></code>. As a result,
there is no need to do anything special to use the API from C++.</p>
</div>
<div class="section" id="useful-macros">
<h2>有用的宏<a class="headerlink" href="#useful-macros" title="永久链接至标题">¶</a></h2>
<p>Python 头文件中定义了一些有用的宏。许多是在靠近它们被使用的地方定义的（例如 <a class="reference internal" href="none.html#c.Py_RETURN_NONE" title="Py_RETURN_NONE"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_RETURN_NONE</span></code></a>）。其他更为通用的则定义在这里。这里所显示的并不是一个完整的列表。</p>
<dl class="macro">
<dt id="c.Py_UNREACHABLE">
<code class="sig-name descname">Py_UNREACHABLE</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNREACHABLE" title="永久链接至目标">¶</a></dt>
<dd><p>这个可以在你有一个不打算被触及的代码路径时使用。例如，当一个 <code class="docutils literal notranslate"><span class="pre">switch</span></code> 语句中所有可能的值都已被 <code class="docutils literal notranslate"><span class="pre">case</span></code> 子句覆盖了，就可将其用在 <code class="docutils literal notranslate"><span class="pre">default:</span></code> 子句中。当你非常想在某个位置放一个 <code class="docutils literal notranslate"><span class="pre">assert(0)</span></code> 或 <code class="docutils literal notranslate"><span class="pre">abort()</span></code> 调用时也可以用这个。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>

<dl class="macro">
<dt id="c.Py_ABS">
<code class="sig-name descname">Py_ABS</code><span class="sig-paren">(</span>x<span class="sig-paren">)</span><a class="headerlink" href="#c.Py_ABS" title="永久链接至目标">¶</a></dt>
<dd><p>返回 <code class="docutils literal notranslate"><span class="pre">x</span></code> 的绝对值。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="macro">
<dt id="c.Py_MIN">
<code class="sig-name descname">Py_MIN</code><span class="sig-paren">(</span>x, y<span class="sig-paren">)</span><a class="headerlink" href="#c.Py_MIN" title="永久链接至目标">¶</a></dt>
<dd><p>返回 <code class="docutils literal notranslate"><span class="pre">x</span></code> 和 <code class="docutils literal notranslate"><span class="pre">y</span></code> 当中的最小值。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="macro">
<dt id="c.Py_MAX">
<code class="sig-name descname">Py_MAX</code><span class="sig-paren">(</span>x, y<span class="sig-paren">)</span><a class="headerlink" href="#c.Py_MAX" title="永久链接至目标">¶</a></dt>
<dd><p>返回 <code class="docutils literal notranslate"><span class="pre">x</span></code> 和 <code class="docutils literal notranslate"><span class="pre">y</span></code> 当中的最大值。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
</dd></dl>

<dl class="macro">
<dt id="c.Py_STRINGIFY">
<code class="sig-name descname">Py_STRINGIFY</code><span class="sig-paren">(</span>x<span class="sig-paren">)</span><a class="headerlink" href="#c.Py_STRINGIFY" title="永久链接至目标">¶</a></dt>
<dd><p>将 <code class="docutils literal notranslate"><span class="pre">x</span></code> 转换为 C 字符串。例如 <code class="docutils literal notranslate"><span class="pre">Py_STRINGIFY(123)</span></code> 返回 <code class="docutils literal notranslate"><span class="pre">&quot;123&quot;</span></code>。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.4 新版功能.</span></p>
</div>
</dd></dl>

<dl class="macro">
<dt id="c.Py_MEMBER_SIZE">
<code class="sig-name descname">Py_MEMBER_SIZE</code><span class="sig-paren">(</span>type, member<span class="sig-paren">)</span><a class="headerlink" href="#c.Py_MEMBER_SIZE" title="永久链接至目标">¶</a></dt>
<dd><p>返回结构 (<code class="docutils literal notranslate"><span class="pre">type</span></code>) <code class="docutils literal notranslate"><span class="pre">member</span></code> 的大小，以字节表示。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.6 新版功能.</span></p>
</div>
</dd></dl>

<dl class="macro">
<dt id="c.Py_CHARMASK">
<code class="sig-name descname">Py_CHARMASK</code><span class="sig-paren">(</span>c<span class="sig-paren">)</span><a class="headerlink" href="#c.Py_CHARMASK" title="永久链接至目标">¶</a></dt>
<dd><p>参数必须为 [-128, 127] 或 [0, 255] 范围内的字符或整数类型。这个宏将 <code class="docutils literal notranslate"><span class="pre">c</span></code> 强制转换为 <code class="docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">char</span></code> 返回。</p>
</dd></dl>

<dl class="macro">
<dt id="c.Py_GETENV">
<code class="sig-name descname">Py_GETENV</code><span class="sig-paren">(</span>s<span class="sig-paren">)</span><a class="headerlink" href="#c.Py_GETENV" title="永久链接至目标">¶</a></dt>
<dd><p>Like <code class="docutils literal notranslate"><span class="pre">getenv(s)</span></code>, but returns <code class="docutils literal notranslate"><span class="pre">NULL</span></code> if <a class="reference internal" href="../using/cmdline.html#cmdoption-e"><code class="xref std std-option docutils literal notranslate"><span class="pre">-E</span></code></a> was passed on the
command line (i.e. if <code class="docutils literal notranslate"><span class="pre">Py_IgnoreEnvironmentFlag</span></code> is set).</p>
</dd></dl>

<dl class="macro">
<dt id="c.Py_UNUSED">
<code class="sig-name descname">Py_UNUSED</code><span class="sig-paren">(</span>arg<span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNUSED" title="永久链接至目标">¶</a></dt>
<dd><p>这个可用于函数定义中未使用的参数以隐藏编译器警告，例如 <code class="docutils literal notranslate"><span class="pre">PyObject*</span> <span class="pre">func(PyObject</span> <span class="pre">*Py_UNUSED(ignored))</span></code>。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.4 新版功能.</span></p>
</div>
</dd></dl>

<dl class="macro">
<dt id="c.PyDoc_STRVAR">
<code class="sig-name descname">PyDoc_STRVAR</code><span class="sig-paren">(</span>name, str<span class="sig-paren">)</span><a class="headerlink" href="#c.PyDoc_STRVAR" title="永久链接至目标">¶</a></dt>
<dd><p>Creates a variable with name <code class="docutils literal notranslate"><span class="pre">name</span></code> that can be used in docstrings.
If Python is built without docstrings, the value will be empty.</p>
<p>Use <a class="reference internal" href="#c.PyDoc_STRVAR" title="PyDoc_STRVAR"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyDoc_STRVAR</span></code></a> for docstrings to support building
Python without docstrings, as specified in <span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0007"><strong>PEP 7</strong></a>.</p>
<p>示例:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyDoc_STRVAR</span><span class="p">(</span><span class="n">pop_doc</span><span class="p">,</span> <span class="s">&quot;Remove and return the rightmost element.&quot;</span><span class="p">);</span>

<span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">deque_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="c1">// ...</span>
    <span class="p">{</span><span class="s">&quot;pop&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyCFunction</span><span class="p">)</span><span class="n">deque_pop</span><span class="p">,</span> <span class="n">METH_NOARGS</span><span class="p">,</span> <span class="n">pop_doc</span><span class="p">},</span>
    <span class="c1">// ...</span>
<span class="p">}</span>
</pre></div>
</div>
</dd></dl>

<dl class="macro">
<dt id="c.PyDoc_STR">
<code class="sig-name descname">PyDoc_STR</code><span class="sig-paren">(</span>str<span class="sig-paren">)</span><a class="headerlink" href="#c.PyDoc_STR" title="永久链接至目标">¶</a></dt>
<dd><p>Creates a docstring for the given input string or an empty string
if docstrings are disabled.</p>
<p>Use <a class="reference internal" href="#c.PyDoc_STR" title="PyDoc_STR"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyDoc_STR</span></code></a> in specifying docstrings to support
building Python without docstrings, as specified in <span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0007"><strong>PEP 7</strong></a>.</p>
<p>示例:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">pysqlite_row_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;keys&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyCFunction</span><span class="p">)</span><span class="n">pysqlite_row_keys</span><span class="p">,</span> <span class="n">METH_NOARGS</span><span class="p">,</span>
        <span class="n">PyDoc_STR</span><span class="p">(</span><span class="s">&quot;Returns the keys of the row.&quot;</span><span class="p">)},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">}</span>
<span class="p">};</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="objects-types-and-reference-counts">
<span id="api-objects"></span><h2>对象、类型和引用计数<a class="headerlink" href="#objects-types-and-reference-counts" title="永久链接至标题">¶</a></h2>
<p id="index-8">大多数 Python/C API 函数都有一个或多个参数以及一个 <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> 类型的返回值。此类型是一个指针，指向表示一个任意 Python 对象的不透明数据类型。由于在大多数情况下（例如赋值、作用域规则和参数传递） Python 语言都会以同样的方式处理所有 Python 对象类型，因此它们由一个单独的 C 类型来表示是很适宜的。几乎所有 Python 对象都生存在堆上：你绝不会声明一个 <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> 类型的自动或静态变量，只有 <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> 类型的指针变量可以被声明。唯一的例外是 type 对象；由于此种对象永远不能被释放，所以它们通常是静态 <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> 对象。</p>
<p>所有 Python 对象（甚至 Python 整数）都有一个 <em class="dfn">type</em> 和一个 <em class="dfn">reference count</em>。对象的类型确定它是什么类型的对象（例如整数、列表或用户定义函数；还有更多，如 <a class="reference internal" href="../reference/datamodel.html#types"><span class="std std-ref">标准类型层级结构</span></a> 中所述）。对于每个众所周知的类型，都有一个宏来检查对象是否属于该类型；例如，当（且仅当） <em>a</em> 所指的对象是 Python 列表时 <code class="docutils literal notranslate"><span class="pre">PyList_Check(a)</span></code> 为真。</p>
<div class="section" id="reference-counts">
<span id="api-refcounts"></span><h3>引用计数<a class="headerlink" href="#reference-counts" title="永久链接至标题">¶</a></h3>
<p>The reference count is important because today's computers have a  finite (and
often severely limited) memory size; it counts how many  different places there
are that have a reference to an object.  Such a  place could be another object,
or a global (or static) C variable, or  a local variable in some C function.
When an object's reference count  becomes zero, the object is deallocated.  If
it contains references to  other objects, their reference count is decremented.
Those other  objects may be deallocated in turn, if this decrement makes their
reference count become zero, and so on.  (There's an obvious problem  with
objects that reference each other here; for now, the solution is  &quot;don't do
that.&quot;)</p>
<p id="index-9">Reference counts are always manipulated explicitly.  The normal way is  to use
the macro <a class="reference internal" href="refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> to increment an object's reference count by one,
and <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> to decrement it by   one.  The <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> macro
is considerably more complex than the incref one, since it must check whether
the reference count becomes zero and then cause the object's deallocator to be
called. The deallocator is a function pointer contained in the object's type
structure.  The type-specific deallocator takes care of decrementing the
reference counts for other objects contained in the object if this is a compound
object type, such as a list, as well as performing any additional finalization
that's needed.  There's no chance that the reference count can overflow; at
least as many bits are used to hold the reference count as there are distinct
memory locations in virtual memory (assuming <code class="docutils literal notranslate"><span class="pre">sizeof(Py_ssize_t)</span> <span class="pre">&gt;=</span> <span class="pre">sizeof(void*)</span></code>).
Thus, the reference count increment is a simple operation.</p>
<p>It is not necessary to increment an object's reference count for every  local
variable that contains a pointer to an object.  In theory, the  object's
reference count goes up by one when the variable is made to  point to it and it
goes down by one when the variable goes out of  scope.  However, these two
cancel each other out, so at the end the  reference count hasn't changed.  The
only real reason to use the  reference count is to prevent the object from being
deallocated as  long as our variable is pointing to it.  If we know that there
is at  least one other reference to the object that lives at least as long as
our variable, there is no need to increment the reference count  temporarily.
An important situation where this arises is in objects  that are passed as
arguments to C functions in an extension module  that are called from Python;
the call mechanism guarantees to hold a  reference to every argument for the
duration of the call.</p>
<p>However, a common pitfall is to extract an object from a list and hold on to it
for a while without incrementing its reference count. Some other operation might
conceivably remove the object from the list, decrementing its reference count
and possible deallocating it. The real danger is that innocent-looking
operations may invoke arbitrary Python code which could do this; there is a code
path which allows control to flow back to the user from a <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>, so
almost any operation is potentially dangerous.</p>
<p>A safe approach is to always use the generic operations (functions  whose name
begins with <code class="docutils literal notranslate"><span class="pre">PyObject_</span></code>, <code class="docutils literal notranslate"><span class="pre">PyNumber_</span></code>, <code class="docutils literal notranslate"><span class="pre">PySequence_</span></code> or <code class="docutils literal notranslate"><span class="pre">PyMapping_</span></code>).
These operations always increment the reference count of the object they return.
This leaves the caller with the responsibility to call <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> when
they are done with the result; this soon becomes second nature.</p>
<div class="section" id="reference-count-details">
<span id="api-refcountdetails"></span><h4>Reference Count Details<a class="headerlink" href="#reference-count-details" title="永久链接至标题">¶</a></h4>
<p>The reference count behavior of functions in the Python/C API is best  explained
in terms of <em>ownership of references</em>.  Ownership pertains to references, never
to objects (objects are not owned: they are always shared).  &quot;Owning a
reference&quot; means being responsible for calling Py_DECREF on it when the
reference is no longer needed.  Ownership can also be transferred, meaning that
the code that receives ownership of the reference then becomes responsible for
eventually decref'ing it by calling <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> or <a class="reference internal" href="refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a>
when it's no longer needed---or passing on this responsibility (usually to its
caller). When a function passes ownership of a reference on to its caller, the
caller is said to receive a <em>new</em> reference.  When no ownership is transferred,
the caller is said to <em>borrow</em> the reference. Nothing needs to be done for a
borrowed reference.</p>
<p>Conversely, when a calling function passes in a reference to an  object, there
are two possibilities: the function <em>steals</em> a  reference to the object, or it
does not.  <em>Stealing a reference</em> means that when you pass a reference to a
function, that function assumes that it now owns that reference, and you are not
responsible for it any longer.</p>
<p id="index-10">Few functions steal references; the two notable exceptions are
<a class="reference internal" href="list.html#c.PyList_SetItem" title="PyList_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_SetItem()</span></code></a> and <a class="reference internal" href="tuple.html#c.PyTuple_SetItem" title="PyTuple_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_SetItem()</span></code></a>, which  steal a reference
to the item (but not to the tuple or list into which the item is put!).  These
functions were designed to steal a reference because of a common idiom for
populating a tuple or list with newly created objects; for example, the code to
create the tuple <code class="docutils literal notranslate"><span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">&quot;three&quot;)</span></code> could look like this (forgetting about
error handling for the moment; a better way to code this is shown below):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">t</span><span class="p">;</span>

<span class="n">t</span> <span class="o">=</span> <span class="n">PyTuple_New</span><span class="p">(</span><span class="mi">3</span><span class="p">);</span>
<span class="n">PyTuple_SetItem</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">PyLong_FromLong</span><span class="p">(</span><span class="mi">1L</span><span class="p">));</span>
<span class="n">PyTuple_SetItem</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">PyLong_FromLong</span><span class="p">(</span><span class="mi">2L</span><span class="p">));</span>
<span class="n">PyTuple_SetItem</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="n">PyUnicode_FromString</span><span class="p">(</span><span class="s">&quot;three&quot;</span><span class="p">));</span>
</pre></div>
</div>
<p>Here, <a class="reference internal" href="long.html#c.PyLong_FromLong" title="PyLong_FromLong"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyLong_FromLong()</span></code></a> returns a new reference which is immediately
stolen by <a class="reference internal" href="tuple.html#c.PyTuple_SetItem" title="PyTuple_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_SetItem()</span></code></a>.  When you want to keep using an object
although the reference to it will be stolen, use <a class="reference internal" href="refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> to grab
another reference before calling the reference-stealing function.</p>
<p>Incidentally, <a class="reference internal" href="tuple.html#c.PyTuple_SetItem" title="PyTuple_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_SetItem()</span></code></a> is the <em>only</em> way to set tuple items;
<a class="reference internal" href="sequence.html#c.PySequence_SetItem" title="PySequence_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_SetItem()</span></code></a> and <a class="reference internal" href="object.html#c.PyObject_SetItem" title="PyObject_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_SetItem()</span></code></a> refuse to do this
since tuples are an immutable data type.  You should only use
<a class="reference internal" href="tuple.html#c.PyTuple_SetItem" title="PyTuple_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_SetItem()</span></code></a> for tuples that you are creating yourself.</p>
<p>Equivalent code for populating a list can be written using <a class="reference internal" href="list.html#c.PyList_New" title="PyList_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_New()</span></code></a>
and <a class="reference internal" href="list.html#c.PyList_SetItem" title="PyList_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_SetItem()</span></code></a>.</p>
<p>However, in practice, you will rarely use these ways of creating and populating
a tuple or list.  There's a generic function, <a class="reference internal" href="arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>, that can
create most common objects from C values, directed by a <em class="dfn">format string</em>.
For example, the above two blocks of code could be replaced by the following
(which also takes care of the error checking):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">tuple</span><span class="p">,</span> <span class="o">*</span><span class="n">list</span><span class="p">;</span>

<span class="n">tuple</span> <span class="o">=</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;(iis)&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s">&quot;three&quot;</span><span class="p">);</span>
<span class="n">list</span> <span class="o">=</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;[iis]&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s">&quot;three&quot;</span><span class="p">);</span>
</pre></div>
</div>
<p>It is much more common to use <a class="reference internal" href="object.html#c.PyObject_SetItem" title="PyObject_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_SetItem()</span></code></a> and friends with items
whose references you are only borrowing, like arguments that were passed in to
the function you are writing.  In that case, their behaviour regarding reference
counts is much saner, since you don't have to increment a reference count so you
can give a reference away (&quot;have it be stolen&quot;).  For example, this function
sets all items of a list (actually, any mutable sequence) to a given item:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span>
<span class="nf">set_all</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">target</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Py_ssize_t</span> <span class="n">i</span><span class="p">,</span> <span class="n">n</span><span class="p">;</span>

    <span class="n">n</span> <span class="o">=</span> <span class="n">PyObject_Length</span><span class="p">(</span><span class="n">target</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">n</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
    <span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">PyObject</span> <span class="o">*</span><span class="n">index</span> <span class="o">=</span> <span class="n">PyLong_FromSsize_t</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">index</span><span class="p">)</span>
            <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">PyObject_SetItem</span><span class="p">(</span><span class="n">target</span><span class="p">,</span> <span class="n">index</span><span class="p">,</span> <span class="n">item</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">index</span><span class="p">);</span>
            <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">index</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p id="index-11">The situation is slightly different for function return values.   While passing
a reference to most functions does not change your  ownership responsibilities
for that reference, many functions that  return a reference to an object give
you ownership of the reference. The reason is simple: in many cases, the
returned object is created  on the fly, and the reference you get is the only
reference to the  object.  Therefore, the generic functions that return object
references, like <a class="reference internal" href="object.html#c.PyObject_GetItem" title="PyObject_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetItem()</span></code></a> and  <a class="reference internal" href="sequence.html#c.PySequence_GetItem" title="PySequence_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_GetItem()</span></code></a>,
always return a new reference (the caller becomes the owner of the reference).</p>
<p>It is important to realize that whether you own a reference returned  by a
function depends on which function you call only --- <em>the plumage</em> (the type of
the object passed as an argument to the function) <em>doesn't enter into it!</em>
Thus, if you  extract an item from a list using <a class="reference internal" href="list.html#c.PyList_GetItem" title="PyList_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_GetItem()</span></code></a>, you
don't own the reference --- but if you obtain the same item from the same list
using <a class="reference internal" href="sequence.html#c.PySequence_GetItem" title="PySequence_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_GetItem()</span></code></a> (which happens to take exactly the same
arguments), you do own a reference to the returned object.</p>
<p id="index-12">Here is an example of how you could write a function that computes the sum of
the items in a list of integers; once using  <a class="reference internal" href="list.html#c.PyList_GetItem" title="PyList_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_GetItem()</span></code></a>, and once
using <a class="reference internal" href="sequence.html#c.PySequence_GetItem" title="PySequence_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_GetItem()</span></code></a>.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">long</span>
<span class="nf">sum_list</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">list</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Py_ssize_t</span> <span class="n">i</span><span class="p">,</span> <span class="n">n</span><span class="p">;</span>
    <span class="kt">long</span> <span class="n">total</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">value</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span><span class="p">;</span>

    <span class="n">n</span> <span class="o">=</span> <span class="n">PyList_Size</span><span class="p">(</span><span class="n">list</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">n</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span> <span class="cm">/* Not a list */</span>
    <span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">item</span> <span class="o">=</span> <span class="n">PyList_GetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="n">i</span><span class="p">);</span> <span class="cm">/* Can&#39;t fail */</span>
        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyLong_Check</span><span class="p">(</span><span class="n">item</span><span class="p">))</span> <span class="k">continue</span><span class="p">;</span> <span class="cm">/* Skip non-integers */</span>
        <span class="n">value</span> <span class="o">=</span> <span class="n">PyLong_AsLong</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">value</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span> <span class="o">&amp;&amp;</span> <span class="n">PyErr_Occurred</span><span class="p">())</span>
            <span class="cm">/* Integer too big to fit in a C long, bail out */</span>
            <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
        <span class="n">total</span> <span class="o">+=</span> <span class="n">value</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">total</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="highlight-c notranslate" id="index-13"><div class="highlight"><pre><span></span><span class="kt">long</span>
<span class="nf">sum_sequence</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">sequence</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Py_ssize_t</span> <span class="n">i</span><span class="p">,</span> <span class="n">n</span><span class="p">;</span>
    <span class="kt">long</span> <span class="n">total</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">value</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span><span class="p">;</span>
    <span class="n">n</span> <span class="o">=</span> <span class="n">PySequence_Length</span><span class="p">(</span><span class="n">sequence</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">n</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span> <span class="cm">/* Has no length */</span>
    <span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">item</span> <span class="o">=</span> <span class="n">PySequence_GetItem</span><span class="p">(</span><span class="n">sequence</span><span class="p">,</span> <span class="n">i</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">item</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
            <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span> <span class="cm">/* Not a sequence, or other failure */</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">PyLong_Check</span><span class="p">(</span><span class="n">item</span><span class="p">))</span> <span class="p">{</span>
            <span class="n">value</span> <span class="o">=</span> <span class="n">PyLong_AsLong</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
            <span class="k">if</span> <span class="p">(</span><span class="n">value</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span> <span class="o">&amp;&amp;</span> <span class="n">PyErr_Occurred</span><span class="p">())</span>
                <span class="cm">/* Integer too big to fit in a C long, bail out */</span>
                <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
            <span class="n">total</span> <span class="o">+=</span> <span class="n">value</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="k">else</span> <span class="p">{</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">item</span><span class="p">);</span> <span class="cm">/* Discard reference ownership */</span>
        <span class="p">}</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">total</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="types">
<span id="api-types"></span><span id="index-14"></span><h3>类型<a class="headerlink" href="#types" title="永久链接至标题">¶</a></h3>
<p>There are few other data types that play a significant role in  the Python/C
API; most are simple C types such as <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>,  <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code>,
<code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> and <code class="xref c c-type docutils literal notranslate"><span class="pre">char*</span></code>.  A few structure types  are used to
describe static tables used to list the functions exported  by a module or the
data attributes of a new object type, and another is used to describe the value
of a complex number.  These will  be discussed together with the functions that
use them.</p>
</div>
</div>
<div class="section" id="exceptions">
<span id="api-exceptions"></span><h2>异常<a class="headerlink" href="#exceptions" title="永久链接至标题">¶</a></h2>
<p>Python程序员只需要处理特定需要处理的错误异常；未处理的异常会自动传递给调用者，然后传递给调用者的调用者，依此类推，直到他们到达顶级解释器，在那里将它们报告给用户并伴随堆栈回溯。</p>
<p id="index-15">For C programmers, however, error checking always has to be explicit.  All
functions in the Python/C API can raise exceptions, unless an explicit claim is
made otherwise in a function's documentation.  In general, when a function
encounters an error, it sets an exception, discards any object references that
it owns, and returns an error indicator.  If not documented otherwise, this
indicator is either <code class="docutils literal notranslate"><span class="pre">NULL</span></code> or <code class="docutils literal notranslate"><span class="pre">-1</span></code>, depending on the function's return type.
A few functions return a Boolean true/false result, with false indicating an
error.  Very few functions return no explicit error indicator or have an
ambiguous return value, and require explicit testing for errors with
<a class="reference internal" href="exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a>.  These exceptions are always explicitly documented.</p>
<p id="index-16">Exception state is maintained in per-thread storage (this is  equivalent to
using global storage in an unthreaded application).  A  thread can be in one of
two states: an exception has occurred, or not. The function
<a class="reference internal" href="exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a> can be used to check for this: it returns a borrowed
reference to the exception type object when an exception has occurred, and
<code class="docutils literal notranslate"><span class="pre">NULL</span></code> otherwise.  There are a number of functions to set the exception state:
<a class="reference internal" href="exceptions.html#c.PyErr_SetString" title="PyErr_SetString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetString()</span></code></a> is the most common (though not the most general)
function to set the exception state, and <a class="reference internal" href="exceptions.html#c.PyErr_Clear" title="PyErr_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Clear()</span></code></a> clears the
exception state.</p>
<p>The full exception state consists of three objects (all of which can  be
<code class="docutils literal notranslate"><span class="pre">NULL</span></code>): the exception type, the corresponding exception  value, and the
traceback.  These have the same meanings as the Python result of
<code class="docutils literal notranslate"><span class="pre">sys.exc_info()</span></code>; however, they are not the same: the Python objects represent
the last exception being handled by a Python  <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> ...
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> statement, while the C level exception state only exists while
an exception is being passed on between C functions until it reaches the Python
bytecode interpreter's  main loop, which takes care of transferring it to
<code class="docutils literal notranslate"><span class="pre">sys.exc_info()</span></code> and friends.</p>
<p id="index-17">Note that starting with Python 1.5, the preferred, thread-safe way to access the
exception state from Python code is to call the function <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>,
which returns the per-thread exception state for Python code.  Also, the
semantics of both ways to access the exception state have changed so that a
function which catches an exception will save and restore its thread's exception
state so as to preserve the exception state of its caller.  This prevents common
bugs in exception handling code caused by an innocent-looking function
overwriting the exception being handled; it also reduces the often unwanted
lifetime extension for objects that are referenced by the stack frames in the
traceback.</p>
<p>As a general principle, a function that calls another function to  perform some
task should check whether the called function raised an  exception, and if so,
pass the exception state on to its caller.  It  should discard any object
references that it owns, and return an  error indicator, but it should <em>not</em> set
another exception --- that would overwrite the exception that was just raised,
and lose important information about the exact cause of the error.</p>
<p id="index-18">A simple example of detecting exceptions and passing them on is shown in the
<code class="xref c c-func docutils literal notranslate"><span class="pre">sum_sequence()</span></code> example above.  It so happens that this example doesn't
need to clean up any owned references when it detects an error.  The following
example function shows some error cleanup.  First, to remind you why you like
Python, we show the equivalent Python code:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">def</span> <span class="n">incr_item</span><span class="p">(</span><span class="n">dict</span><span class="p">,</span> <span class="n">key</span><span class="p">)</span><span class="o">:</span>
    <span class="nl">try</span><span class="p">:</span>
        <span class="n">item</span> <span class="o">=</span> <span class="n">dict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
    <span class="n">except</span> <span class="nl">KeyError</span><span class="p">:</span>
        <span class="n">item</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">dict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">item</span> <span class="o">+</span> <span class="mi">1</span>
</pre></div>
</div>
<p id="index-19">Here is the corresponding C code, in all its glory:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span>
<span class="nf">incr_item</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">dict</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">key</span><span class="p">)</span>
<span class="p">{</span>
    <span class="cm">/* Objects all initialized to NULL for Py_XDECREF */</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">,</span> <span class="o">*</span><span class="n">const_one</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">,</span> <span class="o">*</span><span class="n">incremented_item</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">rv</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span> <span class="cm">/* Return value initialized to -1 (failure) */</span>

    <span class="n">item</span> <span class="o">=</span> <span class="n">PyObject_GetItem</span><span class="p">(</span><span class="n">dict</span><span class="p">,</span> <span class="n">key</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">item</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="cm">/* Handle KeyError only: */</span>
        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyErr_ExceptionMatches</span><span class="p">(</span><span class="n">PyExc_KeyError</span><span class="p">))</span>
            <span class="k">goto</span> <span class="n">error</span><span class="p">;</span>

        <span class="cm">/* Clear the error and use zero: */</span>
        <span class="n">PyErr_Clear</span><span class="p">();</span>
        <span class="n">item</span> <span class="o">=</span> <span class="n">PyLong_FromLong</span><span class="p">(</span><span class="mi">0L</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">item</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
            <span class="k">goto</span> <span class="n">error</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="n">const_one</span> <span class="o">=</span> <span class="n">PyLong_FromLong</span><span class="p">(</span><span class="mi">1L</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">const_one</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">goto</span> <span class="n">error</span><span class="p">;</span>

    <span class="n">incremented_item</span> <span class="o">=</span> <span class="n">PyNumber_Add</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="n">const_one</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">incremented_item</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">goto</span> <span class="n">error</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">PyObject_SetItem</span><span class="p">(</span><span class="n">dict</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">incremented_item</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">goto</span> <span class="n">error</span><span class="p">;</span>
    <span class="n">rv</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="cm">/* Success */</span>
    <span class="cm">/* Continue with cleanup code */</span>

 <span class="nl">error</span><span class="p">:</span>
    <span class="cm">/* Cleanup code, shared by success and failure path */</span>

    <span class="cm">/* Use Py_XDECREF() to ignore NULL references */</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">const_one</span><span class="p">);</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">incremented_item</span><span class="p">);</span>

    <span class="k">return</span> <span class="n">rv</span><span class="p">;</span> <span class="cm">/* -1 for error, 0 for success */</span>
<span class="p">}</span>
</pre></div>
</div>
<span class="target" id="index-20"></span><p id="index-21">This example represents an endorsed use of the <code class="docutils literal notranslate"><span class="pre">goto</span></code> statement  in C!
It illustrates the use of <a class="reference internal" href="exceptions.html#c.PyErr_ExceptionMatches" title="PyErr_ExceptionMatches"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_ExceptionMatches()</span></code></a> and
<a class="reference internal" href="exceptions.html#c.PyErr_Clear" title="PyErr_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Clear()</span></code></a> to handle specific exceptions, and the use of
<a class="reference internal" href="refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a> to dispose of owned references that may be <code class="docutils literal notranslate"><span class="pre">NULL</span></code> (note the
<code class="docutils literal notranslate"><span class="pre">'X'</span></code> in the name; <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> would crash when confronted with a
<code class="docutils literal notranslate"><span class="pre">NULL</span></code> reference).  It is important that the variables used to hold owned
references are initialized to <code class="docutils literal notranslate"><span class="pre">NULL</span></code> for this to work; likewise, the proposed
return value is initialized to <code class="docutils literal notranslate"><span class="pre">-1</span></code> (failure) and only set to success after
the final call made is successful.</p>
</div>
<div class="section" id="embedding-python">
<span id="api-embedding"></span><h2>嵌入Python<a class="headerlink" href="#embedding-python" title="永久链接至标题">¶</a></h2>
<p>The one important task that only embedders (as opposed to extension writers) of
the Python interpreter have to worry about is the initialization, and possibly
the finalization, of the Python interpreter.  Most functionality of the
interpreter can only be used after the interpreter has been initialized.</p>
<p id="index-22">The basic initialization function is <a class="reference internal" href="init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>. This initializes
the table of loaded modules, and creates the fundamental modules
<a class="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code></a>, <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a>, and <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>.  It also
initializes the module search path (<code class="docutils literal notranslate"><span class="pre">sys.path</span></code>).</p>
<p id="index-23"><a class="reference internal" href="init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a> does not set the &quot;script argument list&quot;  (<code class="docutils literal notranslate"><span class="pre">sys.argv</span></code>).
If this variable is needed by Python code that will be executed later, it must
be set explicitly with a call to  <code class="docutils literal notranslate"><span class="pre">PySys_SetArgvEx(argc,</span> <span class="pre">argv,</span> <span class="pre">updatepath)</span></code>
after the call to <a class="reference internal" href="init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>.</p>
<p>On most systems (in particular, on Unix and Windows, although the details are
slightly different), <a class="reference internal" href="init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a> calculates the module search path
based upon its best guess for the location of the standard Python interpreter
executable, assuming that the Python library is found in a fixed location
relative to the Python interpreter executable.  In particular, it looks for a
directory named <code class="file docutils literal notranslate"><span class="pre">lib/python</span><em><span class="pre">X.Y</span></em></code> relative to the parent directory
where the executable named <code class="file docutils literal notranslate"><span class="pre">python</span></code> is found on the shell command search
path (the environment variable <span class="target" id="index-24"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>).</p>
<p>For instance, if the Python executable is found in
<code class="file docutils literal notranslate"><span class="pre">/usr/local/bin/python</span></code>, it will assume that the libraries are in
<code class="file docutils literal notranslate"><span class="pre">/usr/local/lib/python</span><em><span class="pre">X.Y</span></em></code>.  (In fact, this particular path is also
the &quot;fallback&quot; location, used when no executable file named <code class="file docutils literal notranslate"><span class="pre">python</span></code> is
found along <span class="target" id="index-25"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>.)  The user can override this behavior by setting the
environment variable <span class="target" id="index-26"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONHOME"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHOME</span></code></a>, or insert additional directories in
front of the standard path by setting <span class="target" id="index-27"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a>.</p>
<p id="index-28">The embedding application can steer the search by calling
<code class="docutils literal notranslate"><span class="pre">Py_SetProgramName(file)</span></code> <em>before</em> calling  <a class="reference internal" href="init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>.  Note that
<span class="target" id="index-29"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONHOME"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHOME</span></code></a> still overrides this and <span class="target" id="index-30"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> is still
inserted in front of the standard path.  An application that requires total
control has to provide its own implementation of <a class="reference internal" href="init.html#c.Py_GetPath" title="Py_GetPath"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_GetPath()</span></code></a>,
<a class="reference internal" href="init.html#c.Py_GetPrefix" title="Py_GetPrefix"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_GetPrefix()</span></code></a>, <a class="reference internal" href="init.html#c.Py_GetExecPrefix" title="Py_GetExecPrefix"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_GetExecPrefix()</span></code></a>, and
<a class="reference internal" href="init.html#c.Py_GetProgramFullPath" title="Py_GetProgramFullPath"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_GetProgramFullPath()</span></code></a> (all defined in <code class="file docutils literal notranslate"><span class="pre">Modules/getpath.c</span></code>).</p>
<p id="index-31">Sometimes, it is desirable to &quot;uninitialize&quot; Python.  For instance,  the
application may want to start over (make another call to
<a class="reference internal" href="init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>) or the application is simply done with its  use of
Python and wants to free memory allocated by Python.  This can be accomplished
by calling <a class="reference internal" href="init.html#c.Py_FinalizeEx" title="Py_FinalizeEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_FinalizeEx()</span></code></a>.  The function <a class="reference internal" href="init.html#c.Py_IsInitialized" title="Py_IsInitialized"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_IsInitialized()</span></code></a> returns
true if Python is currently in the initialized state.  More information about
these functions is given in a later chapter. Notice that <a class="reference internal" href="init.html#c.Py_FinalizeEx" title="Py_FinalizeEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_FinalizeEx()</span></code></a>
does <em>not</em> free all memory allocated by the Python interpreter, e.g. memory
allocated by extension modules currently cannot be released.</p>
</div>
<div class="section" id="debugging-builds">
<span id="api-debugging"></span><h2>调试构建<a class="headerlink" href="#debugging-builds" title="永久链接至标题">¶</a></h2>
<p>Python can be built with several macros to enable extra checks of the
interpreter and extension modules.  These checks tend to add a large amount of
overhead to the runtime so they are not enabled by default.</p>
<p>A full list of the various types of debugging builds is in the file
<code class="file docutils literal notranslate"><span class="pre">Misc/SpecialBuilds.txt</span></code> in the Python source distribution. Builds are
available that support tracing of reference counts, debugging the memory
allocator, or low-level profiling of the main interpreter loop.  Only the most
frequently-used builds will be described in the remainder of this section.</p>
<p>Compiling the interpreter with the <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_DEBUG</span></code> macro defined produces
what is generally meant by &quot;a debug build&quot; of Python. <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_DEBUG</span></code> is
enabled in the Unix build by adding <code class="docutils literal notranslate"><span class="pre">--with-pydebug</span></code> to the
<code class="file docutils literal notranslate"><span class="pre">./configure</span></code> command.  It is also implied by the presence of the
not-Python-specific <code class="xref c c-macro docutils literal notranslate"><span class="pre">_DEBUG</span></code> macro.  When <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_DEBUG</span></code> is enabled
in the Unix build, compiler optimization is disabled.</p>
<p>除了前面描述的引用计数调试之外，还执行以下额外检查：</p>
<ul class="simple">
<li><p>额外检查将添加到对象分配器。</p></li>
<li><p>额外的检查将添加到解析器和编译器中。</p></li>
<li><p>Downcasts from wide types to narrow types are checked for loss of information.</p></li>
<li><p>许多断言被添加到字典和集合实现中。另外，集合对象包含 <code class="xref py py-meth docutils literal notranslate"><span class="pre">test_c_api()</span></code> 方法。</p></li>
<li><p>添加输入参数的完整性检查到框架创建中。</p></li>
<li><p>使用已知的无效模式初始化整型的存储，以捕获对未初始化数字的引用。</p></li>
<li><p>添加底层跟踪和额外的异常检查到虚拟机的运行时中。</p></li>
<li><p>Extra checks are added to the memory arena implementation.</p></li>
<li><p>添加额外调试到线程模块。</p></li>
</ul>
<p>这里可能没有提到的额外的检查。</p>
<p>Defining <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TRACE_REFS</span></code> enables reference tracing.  When defined, a
circular doubly linked list of active objects is maintained by adding two extra
fields to every <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a>.  Total allocations are tracked as well.  Upon
exit, all existing references are printed.  (In interactive mode this happens
after every statement run by the interpreter.)  Implied by <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_DEBUG</span></code>.</p>
<p>有关更多详细信息，请参阅Python源代码中的 <code class="file docutils literal notranslate"><span class="pre">Misc/SpecialBuilds.txt</span></code> 。</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">目录</a></h3>
  <ul>
<li><a class="reference internal" href="#">概述</a><ul>
<li><a class="reference internal" href="#coding-standards">代码标准</a></li>
<li><a class="reference internal" href="#include-files">包含文件</a></li>
<li><a class="reference internal" href="#useful-macros">有用的宏</a></li>
<li><a class="reference internal" href="#objects-types-and-reference-counts">对象、类型和引用计数</a><ul>
<li><a class="reference internal" href="#reference-counts">引用计数</a><ul>
<li><a class="reference internal" href="#reference-count-details">Reference Count Details</a></li>
</ul>
</li>
<li><a class="reference internal" href="#types">类型</a></li>
</ul>
</li>
<li><a class="reference internal" href="#exceptions">异常</a></li>
<li><a class="reference internal" href="#embedding-python">嵌入Python</a></li>
<li><a class="reference internal" href="#debugging-builds">调试构建</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="index.html"
                        title="上一章">Python/C API 参考手册</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="stable.html"
                        title="下一章">稳定的应用程序二进制接口</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">提交 Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.7/Doc/c-api/intro.rst"
            rel="nofollow">显示源代码
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="stable.html" title="稳定的应用程序二进制接口"
             >下一页</a> |</li>
        <li class="right" >
          <a href="index.html" title="Python/C API 参考手册"
             >上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API 参考手册</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">版权所有</a> 2001-2020, Python Software Foundation.
    <br />
    Python 软件基金会是一个非盈利组织。
    <a href="https://www.python.org/psf/donations/">请捐助。</a>
    <br />
    最后更新于 6月 29, 2020.
    <a href="../bugs.html">发现了问题</a>？
    <br />
    使用<a href="http://sphinx.pocoo.org/">Sphinx</a>2.3.1 创建。
    </div>

  </body>
</html>